/**
 * @desc 微信小程序授权相关
 * @author chend
 */
// import qs from 'qs'
const {loginApi} = require('./apiConfig/apiList/luban')
class Auth {
  constructor(timeout = 10 * 60 * 1000) {
    console.log('小程序授权初始化...');
    this.timeout = timeout;
    this.programInit();
  }

  // 检查登录态是否过期
  checkSession() {
    return new Promise(resolve => {
      wx.checkSession({
        success: () => resolve(false),
        fail: () => resolve(true)
      });
    });
  }

  // 更新sessionId
  updateSessionInfo() {
    this.login().then(code => {
      this.wxAuth(code);
      wx.setStorageSync('openCode', code)
    })
  }

  // 调用接口获取登录凭证
  login = () => {
    return new Promise(resolve => {
      wx.login({
        success: (res) => {
          console.log('wxCode', res)
          resolve(res.code)
        }
      });
    });
  };

  // 程序初始化
  programInit() {
    // 定时刷新sessionId
    this.updateSessionInfo();
    setInterval(() => {
      this.updateSessionInfo();
    }, this.timeout);
  }

  // wx.request发送code返回自定义登录态
  wxAuth(code) {
    loginApi({code}).then(res => {
      if(res.code !== 200) {return}
      const {
        loginType = '',
        maOpenId,
        maSessionKey,
        maUnionId,
        toBind,
        authToken = '',
        schoolName = '',
        subscribeStatus='',
        loginUser,
      } = res.data;
      console.log('loginUser', loginUser)
      this.checkAndAuthorize('scope.userInfo')
      wx.setStorageSync('userRole', loginType);
      wx.setStorageSync('loginData', {
        loginType,
        maOpenId,
        maSessionKey,
        maUnionId,
        toBind,
        authToken,
        schoolName,
        code,
        subscribeStatus,
        loginUser
      })
      console.log("登录数据:",wx.getStorageSync('loginData'))
    });
  }
  // 检查用户是否已经授权 
  checkAndAuthorize (scope) {
    let that = this;
    console.log('checkAndAuthorize', scope)
    wx.getSetting({
      success(res) {
        console.log('getSetting', res)
        if (!res.authSetting[scope]) {
          wx.authorize({
            scope: scope,
            success() {
            },
            fail(e){
              console.error(e)
              that.navigateToLogin();
            }
          })
        } else {
        }
      },
      fail(e){
        console.error(e)
      }
    })
  }

  // 导航到登录页面
  navigateToLogin() {
    const url = '/pages/authLogin/index';
    if (getCurrentPages().pop().route !== url)  {
      wx.redirectTo({ url });
    }
  }

}

export default Auth;
